<?php


namespace app\controller\api;


use app\controller\api\Base;
use app\model\ConfigModel;
use app\model\DeliveryAttachModel;
use app\model\GoodsModel;
use app\model\QuotationModel;
use app\model\QuotationTransportModel;
use app\model\ReleaseScopeModel;
use app\model\SizeModel;
use app\model\VehicleModel;
use app\Request;
use app\validate\QuotationCheck;
use think\App;
use think\facade\Db;
use app\model\DeliveryModel;
use app\model\AddressModel;

class Purchaseorder extends Base
{
    public $token;
    public $version;
    public $lang;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->token = $this->request->header('xzdToken');
        $this->version = $this->request->header('version');
        $this->lang = $this->request->header('lang');
    }


    /**
     * @param Request $request
     * @notes 采购单列表我买的
     * @author: zzk
     */
    public function purchase_list(Request $request)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $page = isset($param['page']) ? $param['page'] : 1;
            $limit = isset($param['limit']) ? $param['limit'] : 10;

            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }

            $where = [];

            $where[] = ['a.publish_user_id','=',$param['user_id']];
            if(isset($param['status']) && $param['status']){
                $where[] = ['a.status','=',$param['status']];
            }else{
                $where[] = ['a.status','=',1];
            }
            $list = Db::connect('fast_mysql')
                ->table('fa_purchase_info')->alias('a')
                ->join('fa_quotation b','b.purchase_info_id = a.id and b.status = 1')
                ->join('fa_user c','c.id = b.user_id','left')
                ->join('fa_user_info d','d.user_id = c.id','left')
                ->field('a.id as order_id,a.product_name,a.product_name_ru,a.amount,a.status,a.category_id,a.product_img_urls,a.order_number,b.price,b.currency,b.user_id,c.username,c.username_ru,c.avatar,d.country')
                ->where($where)->page($page,$limit)->select()->toarray();
           foreach ($list as $k=>&$v){
              $v['category_name'] = Db::connect('shop_mysql')->table('ddwx_shop_category')->where('id',$v['category_id'])->value('name');
              $settlement = Db::connect('fast_mysql')->table('fa_settlement')->where('purchase_id',$v['order_id'])->find();
              if($v['status'] == 4 && $settlement){
                  $v['status'] = 6;//已结算状态
              }
           }
           return json(['code' => 200,'message' => '成功','data' => $list]);
        } catch (\Exception $e) {
            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }

    }


    /**
     * @param Request $request
     * @notes 采购单我买的详情
     * @author: zzk
     */
    public function purchase_detaile(Request $request)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $where = [];
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!isset($param['order_id'])){
                return json(['code' => 400,'message' => '参数错误','data' => []]);
            }
            $where[] = ['a.id','=',$param['order_id']];

            $data = Db::connect('fast_mysql')
                ->table('fa_purchase_info')->alias('a')
                ->join('fa_quotation b','b.purchase_info_id = a.id','left')
                ->join('fa_user c','c.id = b.user_id','left')
                ->join('fa_user_info d','d.user_id = c.id','left')
                ->field('a.id as order_id,a.product_name,a.product_name_ru,a.destination,a.destination_ru,a.mailing_type,a.status,a.mailing_type,a.shipping_fee,a.amount,a.category_id,a.product_img_urls,a.order_number,b.price,b.currency,b.user_id,b.address,b.address_ru,b.account_number_img,b.create_time,c.username,c.username_ru,c.avatar,d.country')
                ->where($where)->find();
            $settlement_info =  Db::connect('fast_mysql')
                ->table('fa_settlement')->where('purchase_id',$data['order_id'])->find() ?? null;//获取结算信息
            $data['category_name'] = Db::connect('shop_mysql')->table('ddwx_shop_category')->where('id',$data['category_id'])->value('name');

            $total_price = bcadd($data['price'],$data['shipping_fee'],2);
            $data['total_price'] = $total_price;
            $data['after_sales'] = Db::connect('fast_mysql')
                ->table('fa_after_sales')->where('purchase_id',$data['order_id'])->find() ?? null;//获取售后详情
            $data['pu_comment'] = Db::connect('fast_mysql')
                ->table('fa_pu_comment')->where('purchase_id',$data['order_id'])->find() ?? null;//获取评论
            if($data['pu_comment']){
                $data['pu_comment']['user_info'] =  Db::connect('fast_mysql')
                    ->table('fa_user')->where('id',$data['pu_comment']['user_id'])->field('username,avatar')->find();
            }

            $data['settlement_info'] = $settlement_info;//获取结算信息
            if($data['status'] == 4 && $settlement_info){
                $data['status'] = 6;//已结算状态
            }
            return json(['code' => 200,'message' => '成功','data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }

    }

    /**
     * @param Request $request
     * @notes 采购单列表我卖的
     * @author: zzk
     */
    public function sell_list(Request $request)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $page = isset($param['page']) ? $param['page'] : 1;
            $limit = isset($param['limit']) ? $param['limit'] : 10;
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            $where = [];
            $where[] = ['a.status','=',1];
            $where[] = ['a.user_id','=',$param['user_id']];
            if(isset($param['status']) && $param['status']){
                $where[] = ['b.status','=',$param['status']];
            }else{
                $where[] = ['b.status','=',1];
            }
            $list = Db::connect('fast_mysql')
                ->table('fa_quotation')->alias('a')
                ->join('fa_purchase_info b','a.purchase_info_id = b.id')
                ->join('fa_user c','c.id = b.publish_user_id','left')
                ->join('fa_user_info d','d.user_id = c.id','left')
                ->field('a.id,a.product_name,a.product_name_ru,a.price,a.currency,b.amount,b.category_id,b.id as order_id,b.order_number,b.publish_user_id,b.status,b.mailing_type,b.product_img_urls,c.username,c.username_ru,c.avatar,d.country')
                ->where($where)->page($page,$limit)->select()->toarray();
            foreach ($list as $k=>&$v){
                $v['category_name'] = Db::connect('shop_mysql')->table('ddwx_shop_category')->where('id',$v['category_id'])->value('name');
                $settlement = Db::connect('fast_mysql')->table('fa_settlement')->where('purchase_id',$v['order_id'])->find();
                if($v['status'] == 4 && $settlement){
                    $v['status'] = 6;//已结算状态
                }
            }
            return json(['code' => 200,'message' => '成功','data' => $list]);
        } catch (\Exception $e) {
            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }

    }

    /**
     * @param Request $request
     * @notes 采购单我卖的详情
     * @author: zzk
     */
    public function sell_detaile(Request $request)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            $where = [];
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!isset($param['id'])){
                return json(['code' => 400,'message' => '参数错误','data' => []]);
            }
            $where[] = ['b.id','=',$param['id']];

            $data = Db::connect('fast_mysql')
                ->table('fa_quotation')->alias('b')
                ->join('fa_purchase_info a','a.id = b.purchase_info_id','left')
                ->join('fa_user c','c.id = a.publish_user_id','left')
                ->join('fa_user_info d','d.user_id = c.id','left')
                ->field('a.id as order_id,a.product_name,a.product_name_ru,a.destination,a.destination_ru,a.status,a.publish_user_id,a.mailing_type,a.mailing_type,a.shipping_fee,a.amount,a.category_id,a.product_img_urls,a.order_number,b.id,b.price,b.currency,b.address,b.address_ru,b.account_number_img,b.create_time,c.username,c.username_ru,c.avatar,d.country')
                ->where($where)->find();
           $settlement_info =  Db::connect('fast_mysql')
                ->table('fa_settlement')->where('purchase_id',$data['order_id'])->find() ?? null;//获取结算信息
            $data['category_name'] = Db::connect('shop_mysql')->table('ddwx_shop_category')->where('id',$data['category_id'])->value('name');
            $total_price = bcadd($data['price'],$data['shipping_fee'],2);
            $data['total_price'] = $total_price;
            $data['after_sales'] = Db::connect('fast_mysql')
                ->table('fa_after_sales')->where('purchase_id',$data['order_id'])->find() ?? null;//获取售后详情
            $data['pu_comment'] = Db::connect('fast_mysql')
                ->table('fa_pu_comment')->where('purchase_id',$data['order_id'])->find() ?? null;//获取评论
            if($data['pu_comment']){
                $data['pu_comment']['user_info'] =  Db::connect('fast_mysql')
                    ->table('fa_user')->where('id',$data['pu_comment']['user_id'])->field('username,avatar')->find();
            }
            $data['settlement_info'] =$settlement_info;
            if($data['status'] == 4 && $settlement_info){
                $data['status'] = 6;//已结算状态
            }
            return json(['code' => 200,'message' => '成功','data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }

    }


    /**
     * @param Request $request
     * @notes 售后申请
     * @author: zzk
     */
    public function add_after_sales(Request $request)
    {
        try {
            $param = $request->post();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;

            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!$param['order_id']){
                return json(['code' => 400,'message' => '缺少订单id','data' => []]);
            }

            if(isset($param['buyer_agree_status'])){

                if(!$param['platform_compensation_ratio']){
                    return json(['code' => 400,'message' => '请选择平台赔付比例','data' => []]);
                }
            }else{
                if(!$param['compensation_ratio']){
                    return json(['code' => 400,'message' => '请选择赔付比例','data' => []]);
                }
                if(!$param['reason']){
                    return json(['code' => 400,'message' => '请填写申请原因','data' => []]);
                }
                if(!$param['image_url']){
                    return json(['code' => 400,'message' => '请上传图片','data' => []]);
                }
            }

            //开启事务
            Db::startTrans();
            $data = [
                'purchase_id'                   => $param['order_id'],
                'user_id'                       => $param['user_id'],
                'compensation_ratio'            => $param['compensation_ratio'],
                'reason'                        => $param['reason'] ?? '',
                'image_url'                     => $param['image_url'] ?? '',
                'video_url'                     => $param['video_url'] ?? '',
                'platform_compensation_ratio'   => $param['platform_compensation_ratio'] ?? '',
                'buyer_agree_status'            => isset($param['buyer_agree_status']) ? $param['buyer_agree_status'] :  0,
                'create_time'                   => date('Y-m-d H:i:s'),
            ];
            $insert_res = Db::connect("fast_mysql")->table("fa_after_sales")->insert($data);//增加售后信息
            if(!$insert_res){
                //回滚事务
                Db::rollback();
                return json(['code' => 400,'message' => '申请失败','data' => []]);
            }
            //修改为售后状态
            $update_purchase_status = Db::connect("fast_mysql")->table("fa_purchase_info")->where('id',$param['order_id'])->update(['status'=>5]);
           if(!$update_purchase_status){
               //回滚事务
               Db::rollback();
               return json(['code' => 400,'message' => '申请失败','data' => []]);
           }
            //提交事务
            Db::commit();
            return json(['code' => 200,'message' => '申请成功','data' => []]);
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }

    }

    /**
     * @param Request $request
     * @notes 卖方同意申请
     * @author: zzk
     */
    public function seller_operate(Request $request){
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!$param['after_id']){
                return json(['code' => 400,'message' => '缺少售后id','data' => []]);
            }
            if(!$param['order_id']){
                return json(['code' => 400,'message' => '缺少订单id','data' => []]);
            }
            if(!$param['status']){
                return json(['code' => 400,'message' => '缺少状态','data' => []]);
            }
            $data = [];
            if($param['seller_agree_status']){
                $data['seller_agree_status'] = $param['seller_agree_status'];
            }
            //开启事务
            Db::startTrans();
            $data['status'] = $param['status'];
            $data['done_time'] = date('Y-m-d H:i:s');
            $after_update_res = Db::connect("fast_mysql")
                ->table("fa_after_sales")
                ->where('id',$param['after_id'])->update($data);//修改为双方同意

            if(!$after_update_res){
                //回滚事务
                Db::rollback();
                return json(['code' => 400,'message' => '操作失败','data' => []]);
            }

            //修改为已完成状态
            $update_purchase_status = Db::connect("fast_mysql")
                ->table("fa_purchase_info")
                ->where('id',$param['order_id'])
                ->update(['status'=>4,'done_time'=>date('Y-m-d H:i:s')]);
            if(!$update_purchase_status){
                //回滚事务
                Db::rollback();
                return json(['code' => 400,'message' => '申请失败','data' => []]);
            }
            //提交事务
            Db::commit();
            return json(['code' => 200,'message' => '操作成功','data' => []]);
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }
    }

    /**
     * @param Request $request
     * @notes 上传支付凭证
     * @author: zzk
     */
    public function up_payment_voucher(Request $request){
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!$param['order_id']){
                return json(['code' => 400,'message' => '缺少订单id','data' => []]);
            }

            if(!$param['payment_voucher']){
                return json(['code' => 400,'message' => '缺少付款凭证','data' => []]);
            }
            $after_update_res = Db::connect("fast_mysql")
                ->table("fa_purchase_info")
                ->where('id',$param['order_id'])->update(['payment_voucher'=>$param['payment_voucher'],'status'=>2]);//上传付款凭证

            if(!$after_update_res){
                return json(['code' => 400,'message' => '操作失败','data' => []]);
            }
            return json(['code' => 200,'message' => '操作成功','data' => []]);
        } catch (\Exception $e) {

            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }
    }

    /**
     * @param Request $request
     * @notes 关联运踪
     * @author: zzk
     */

    public function yuntrace_update(Request $request)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!$param['order_id']){
                return json(['code' => 400,'message' => '缺少订单id','data' => []]);
            }

            if(!$param['yuntrace_id']){
                return json(['code' => 400,'message' => '缺少运踪id','data' => []]);
            }
            $after_update_res = Db::connect("fast_mysql")
                ->table("fa_purchase_info")
                ->where('id',$param['order_id'])->update(['yuntrace_id'=>$param['yuntrace_id'],'status'=>3]);

            if(!$after_update_res){
                return json(['code' => 400,'message' => '修改失败','data' => []]);
            }
            return json(['code' => 200,'message' => '操作成功','data' => []]);
        } catch (\Exception $e) {

            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }
    }


    /**
     * @param Request $request
     * @notes 同意付款 修改订单已完成状态
     * @author: zzk
     */
    public function confirm_pay(Request $request)
    {
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!$param['order_id']){
                return json(['code' => 400,'message' => '缺少订单id','data' => []]);
            }

            $after_update_res = Db::connect("fast_mysql")
                ->table("fa_purchase_info")
                ->where('id',$param['order_id'])->update(['status'=>4,'done_time'=>date('Y-m-d H:i:s')]);

            if(!$after_update_res){
                return json(['code' => 400,'message' => '修改失败','data' => []]);
            }
            return json(['code' => 200,'message' => '操作成功','data' => []]);
        } catch (\Exception $e) {

            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }
    }

    /**
     * @param Request $request
     * @notes 修改运费
     * @author: zzk
     */
    public function up_shipping_fee(Request $request){
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!$param['order_id']){
                return json(['code' => 400,'message' => '缺少订单id','data' => []]);
            }

            if(empty($param['shipping_fee'])){
                return json(['code' => 400,'message' => '请输入运费','data' => []]);
            }
            $shipping_fee = Db::connect("fast_mysql")->table("fa_purchase_info")->where('id',$param['order_id'])->value('shipping_fee');

            if($shipping_fee!='0.00'){
                if($param['shipping_fee']>$shipping_fee){
                    return json(['code' => 400,'message' => '本次输入运费不可高于上次填报的运费','data' => []]);
                }
            }

            $after_update_res = Db::connect("fast_mysql")
                ->table("fa_purchase_info")
                ->where('id',$param['order_id'])->update(['shipping_fee'=>$param['shipping_fee']]);//修改为双方同意

            if(!$after_update_res){
                return json(['code' => 400,'message' => '修改失败','data' => []]);
            }
            return json(['code' => 200,'message' => '操作成功','data' => []]);
        } catch (\Exception $e) {

            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }
    }

    /**
     * @param Request $request
     * @notes 添加评价
     * @author: zzk
     */
    public function add_comment(Request $request){
        try {
            $param = $request->param();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;
            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!$param['order_id']){
                return json(['code' => 400,'message' => '缺少订单id','data' => []]);
            }

            if(!$param['star']){
                return json(['code' => 400,'message' => '请选择星级','data' => []]);
            }
            if(!$param['content']){
                return json(['code' => 400,'message' => '请填写评价内容','data' => []]);
            }

            $data = [
                'purchase_id'   => $param['order_id'],
                'user_id'       => $param['user_id'],
                'star'          => $param['star'],
                'content'       => $param['content'],
                'create_time'   => date('Y-m-d H:i:s'),
            ];
            $add_res = Db::connect("fast_mysql")
                ->table("fa_pu_comment")
                ->insert($data);//添加评价

            if(!$add_res){
                return json(['code' => 400,'message' => '评价失败','data' => []]);
            }
            return json(['code' => 200,'message' => '评价成功','data' => []]);
        } catch (\Exception $e) {

            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }
    }

    /**
     * 售后详情
     * @param Request $request
     * @return mixed
     */
    public function after_sales_detail(Request $request){
        $param = $request->param();
        $param['token'] = $this->token;
        $param['version'] = $this->version;
        $param['lang'] = $this->lang;
        if(!isset($param['token']) || !isset($param['user_id'])){
            return json(['code' => 400,'message' => '请先登录','data' => []]);
        }
        if(!$param['order_id']){
            return json(['code' => 400,'message' => '缺少订单id','data' => []]);
        }
        $info = Db::connect("fast_mysql")
            ->table("fa_after_sales")->where('purchase_id',$param['order_id'])->find();
        if($info){
            $info['user_info'] = Db::connect("fast_mysql")
                ->table("fa_user")->alias('a')
                ->join('fa_user_info b','a.id = b.user_id')
                ->where('a.id',$info['user_id'])
                ->field('a.username,a.avatar,b.country')->find();
        }
        return json(['code' => 200,'message' => '成功','data' => $info]);
    }




    /**
     * @param Request $request
     * @notes 修改售后申请
     * @author: zzk
     */
    public function update_after_sales(Request $request)
    {
        try {
            $param = $request->post();
            $param['token'] = $this->token;
            $param['version'] = $this->version;
            $param['lang'] = $this->lang;

            if(!isset($param['token']) || !isset($param['user_id'])){
                return json(['code' => 400,'message' => '请先登录','data' => []]);
            }
            if(!$param['after_id']){
                return json(['code' => 400,'message' => '缺少售后id','data' => []]);
            }

            if(isset($param['buyer_agree_status'])){

                if(!$param['platform_compensation_ratio']){
                    return json(['code' => 400,'message' => '请选择平台赔付比例','data' => []]);
                }
            }else{
                if(!$param['compensation_ratio']){
                    return json(['code' => 400,'message' => '请选择赔付比例','data' => []]);
                }
                if(!$param['reason']){
                    return json(['code' => 400,'message' => '请填写申请原因','data' => []]);
                }
                if(!$param['image_url']){
                    return json(['code' => 400,'message' => '请上传图片','data' => []]);
                }
            }
            $data = [
                'purchase_id'                   => $param['order_id'],
                'user_id'                       => $param['user_id'],
                'compensation_ratio'            => $param['compensation_ratio'],
                'reason'                        => $param['reason'] ?? '',
                'image_url'                     => $param['image_url'] ?? '',
                'video_url'                     => $param['video_url'] ?? '',
                'platform_compensation_ratio'   => $param['platform_compensation_ratio'] ?? '',
                'buyer_agree_status'            => isset($param['buyer_agree_status']) ? $param['buyer_agree_status'] :  0,
                'create_time'                   => date('Y-m-d H:i:s'),
            ];
            $up_res = Db::connect("fast_mysql")->table("fa_after_sales")->where('id',$param['after_id'])->update($data);//增加售后信息
            if(!$up_res){
                return json(['code' => 400,'message' => '申请失败','data' => []]);
            }
            return json(['code' => 200,'message' => '申请成功','data' => []]);
        } catch (\Exception $e) {

            return json(['code' => 400,'message' => $e->getMessage(),'data' => []]);
        }

    }

}